# utils.py
import os
from PIL import Image, ImageOps
from flask import current_app
from werkzeug.utils import secure_filename

# 检查文件扩展名是否允许
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in current_app.config['ALLOWED_EXTENSIONS']

# 保存上传的图片并生成多种尺寸的缩略图
def save_image(file):
    # 确保上传目录存在
    upload_folder = current_app.config['UPLOAD_FOLDER']
    os.makedirs(upload_folder, exist_ok=True)
    
    # 生成安全的文件名
    filename = secure_filename(file.filename)
    
    # 保存原始图片
    file_path = os.path.join(upload_folder, filename)
    file.save(file_path)
    
    # 生成不同尺寸的缩略图
    try:
        img = Image.open(file_path)
        
        # 确保图片方向正确（处理手机拍摄的照片）
        img = ImageOps.exif_transpose(img)
        
        # 生成小尺寸缩略图 (用于列表显示)
        small_thumb = img.copy()
        small_thumb.thumbnail((300, 300))
        small_thumb_name = f"thumb_small_{filename}"
        small_thumb_path = os.path.join(upload_folder, small_thumb_name)
        small_thumb.save(small_thumb_path, optimize=True, quality=85)
        
        # 生成中等尺寸缩略图 (用于详情页)
        medium_thumb = img.copy()
        medium_thumb.thumbnail((800, 600))
        medium_thumb_name = f"thumb_medium_{filename}"
        medium_thumb_path = os.path.join(upload_folder, medium_thumb_name)
        medium_thumb.save(medium_thumb_path, optimize=True, quality=85)
        
        # 生成大尺寸缩略图 (用于预览)
        large_thumb = img.copy()
        large_thumb.thumbnail((1200, 900))
        large_thumb_name = f"thumb_large_{filename}"
        large_thumb_path = os.path.join(upload_folder, large_thumb_name)
        large_thumb.save(large_thumb_path, optimize=True, quality=85)
        
        # 如果原始图片太大，压缩原始图片
        if os.path.getsize(file_path) > 5 * 1024 * 1024:  # 大于5MB
            # 调整原始图片大小
            img.thumbnail((1920, 1080))  # 最大1920x1080
            img.save(file_path, optimize=True, quality=85)
        
        return filename, small_thumb_name, medium_thumb_name, large_thumb_name
    except Exception as e:
        print(f"处理图片时出错: {e}")
        # 如果处理失败，删除已保存的文件
        if os.path.exists(file_path):
            os.remove(file_path)
        raise e

# 保存用户头像
def save_avatar(file):
    # 确保上传目录存在
    upload_folder = current_app.config['UPLOAD_FOLDER']
    os.makedirs(upload_folder, exist_ok=True)
    
    # 生成安全的文件名
    filename = secure_filename(file.filename)
    # 为头像文件添加 avatar_ 前缀以区分普通图片
    avatar_filename = f"avatar_{filename}"
    
    # 保存头像文件
    file_path = os.path.join(upload_folder, avatar_filename)
    file.save(file_path)
    
    # 处理头像图片
    try:
        img = Image.open(file_path)
        
        # 确保图片方向正确
        img = ImageOps.exif_transpose(img)
        
        # 转换为RGB模式（处理PNG透明背景）
        if img.mode in ('RGBA', 'LA', 'P'):
            # 创建白色背景
            background = Image.new('RGB', img.size, (255, 255, 255))
            if img.mode == 'P':
                img = img.convert('RGBA')
            background.paste(img, mask=img.split()[-1] if img.mode in ('RGBA', 'LA') else None)
            img = background
        
        # 调整头像尺寸为正方形
        size = min(img.size)
        left = (img.width - size) // 2
        top = (img.height - size) // 2
        right = left + size
        bottom = top + size
        img = img.crop((left, top, right, bottom))
        
        # 调整为300x300像素
        img = img.resize((300, 300))
        img.save(file_path, optimize=True, quality=90)
        
        return avatar_filename
    except Exception as e:
        print(f"处理头像时出错: {e}")
        # 如果处理失败，删除已保存的文件
        if os.path.exists(file_path):
            os.remove(file_path)
        raise e
    